<template>
  <view class="recharge-container">
    <!-- 头部 -->
    <view class="header">
      <view class="balance-info">
        <text class="balance-label">账户余额</text>
        <text class="balance-amount">¥{{ userBalance.toFixed(2) }}</text>
      </view>
      <view class="recharge-stats">
        <view class="stat-item">
          <text class="stat-label">累计充值</text>
          <text class="stat-value">¥{{ totalRechargeAmount.toFixed(2) }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">充值次数</text>
          <text class="stat-value">{{ rechargeCount }}次</text>
        </view>
      </view>
    </view>

    <!-- 充值金额选择 -->
    <view class="amount-section">
      <text class="section-title">选择充值金额</text>
      <view class="amount-grid">
        <view 
          v-for="amount in presetAmounts" 
          :key="amount"
          class="amount-item"
          :class="{ active: selectedAmount === amount }"
          @click="selectAmount(amount)"
        >
          <text class="amount-text">¥{{ amount }}</text>
        </view>
        <view 
          class="amount-item custom"
          :class="{ active: isCustomAmount }"
          @click="showCustomAmountInput = true"
        >
          <text class="amount-text">自定义</text>
        </view>
      </view>
      
      <!-- 自定义金额输入 -->
      <view v-if="showCustomAmountInput" class="custom-amount-input">
        <input 
          v-model="customAmount"
          type="number"
          placeholder="请输入充值金额"
          class="amount-input"
          @blur="validateCustomAmount"
        />
        <text class="amount-tip">最低1元，最高10000元</text>
      </view>
    </view>

    <!-- 支付方式选择 -->
    <view class="payment-section">
      <text class="section-title">选择支付方式</text>
      <view class="payment-methods">
        <view 
          class="payment-method"
          :class="{ active: selectedPaymentMethod === 'WECHAT' }"
          @click="selectPaymentMethod('WECHAT')"
        >
          <image class="payment-icon" src="/static/images/wechat-pay.png" />
          <text class="payment-name">微信支付</text>
          <view class="payment-check" v-if="selectedPaymentMethod === 'WECHAT'">
            <text class="check-icon">✓</text>
          </view>
        </view>
        <view 
          class="payment-method"
          :class="{ active: selectedPaymentMethod === 'ALIPAY' }"
          @click="selectPaymentMethod('ALIPAY')"
        >
          <image class="payment-icon" src="/static/images/alipay.png" />
          <text class="payment-name">支付宝</text>
          <view class="payment-check" v-if="selectedPaymentMethod === 'ALIPAY'">
            <text class="check-icon">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 充值按钮 -->
    <view class="recharge-button-section">
      <button 
        class="recharge-button"
        :class="{ disabled: !canRecharge }"
        :disabled="!canRecharge"
        @click="handleRecharge"
      >
        <text class="button-text">立即充值 ¥{{ finalAmount.toFixed(2) }}</text>
      </button>
    </view>

    <!-- 充值记录 -->
    <view class="records-section">
      <view class="records-header">
        <text class="section-title">充值记录</text>
        <text class="refresh-btn" @click="loadRechargeRecords">刷新</text>
      </view>
      <view class="records-list">
        <view 
          v-for="record in rechargeRecords" 
          :key="record.id"
          class="record-item"
        >
          <view class="record-info">
            <text class="record-amount">¥{{ record.amount }}</text>
            <text class="record-method">{{ getPaymentMethodName(record.paymentMethod) }}</text>
          </view>
          <view class="record-status">
            <text class="status-text" :class="getStatusClass(record.paymentStatus)">
              {{ getStatusText(record.paymentStatus) }}
            </text>
            <text class="record-time">{{ formatTime(record.createTime) }}</text>
          </view>
        </view>
        <view v-if="rechargeRecords.length === 0" class="empty-records">
          <text class="empty-text">暂无充值记录</text>
        </view>
      </view>
    </view>

    <!-- 加载提示 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-content">
        <text class="loading-text">处理中...</text>
      </view>
    </view>
  </view>
</template>

<script>
import { NETWORK_CONFIG } from '@/config/network.js'

export default {
  name: 'RechargePage',
  data() {
    return {
      userId: null,
      userBalance: 0,
      totalRechargeAmount: 0,
      rechargeCount: 0,
      selectedAmount: 0,
      customAmount: '',
      showCustomAmountInput: false,
      selectedPaymentMethod: '',
      rechargeRecords: [],
      loading: false,
      presetAmounts: [10, 20, 50, 100, 200, 500]
    }
  },
  computed: {
    isCustomAmount() {
      return this.showCustomAmountInput && this.customAmount && !this.presetAmounts.includes(parseFloat(this.customAmount))
    },
    finalAmount() {
      if (this.isCustomAmount) {
        return parseFloat(this.customAmount) || 0
      }
      return this.selectedAmount
    },
    canRecharge() {
      return this.finalAmount > 0 && this.selectedPaymentMethod && !this.loading
    }
  },
  onLoad(options) {
    this.userId = options.userId || 1 // 默认用户ID，实际应该从登录状态获取
    this.loadAccountInfo()
    this.loadRechargeRecords()
  },
  methods: {
    // 加载账户信息
    async loadAccountInfo() {
      try {
        const token = uni.getStorageSync('accessToken')
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/recharge/account`,
          method: 'GET',
          data: { userId: this.userId },
          header: { 'Access-Token': `Bearer ${token}` }
        })
        
        if (response.data.success) {
          const data = response.data.data
          this.userBalance = parseFloat(data.balance) || 0
          this.totalRechargeAmount = parseFloat(data.totalRechargeAmount) || 0
          this.rechargeCount = data.rechargeCount || 0
        }
      } catch (error) {
        console.error('加载账户信息失败:', error)
        uni.showToast({
          title: '加载账户信息失败',
          icon: 'none'
        })
      }
    },
    
    // 加载充值记录
    async loadRechargeRecords() {
      try {
        const token = uni.getStorageSync('accessToken')
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/recharge/records`,
          method: 'GET',
          data: { userId: this.userId },
          header: { 'Access-Token': `Bearer ${token}` }
        })
        
        if (response.data.success) {
          this.rechargeRecords = response.data.data || []
        }
      } catch (error) {
        console.error('加载充值记录失败:', error)
      }
    },
    
    // 选择充值金额
    selectAmount(amount) {
      this.selectedAmount = amount
      this.showCustomAmountInput = false
      this.customAmount = ''
    },
    
    // 验证自定义金额
    validateCustomAmount() {
      const amount = parseFloat(this.customAmount)
      if (amount < 1 || amount > 10000) {
        uni.showToast({
          title: '充值金额必须在1-10000元之间',
          icon: 'none'
        })
        this.customAmount = ''
        return false
      }
      this.selectedAmount = 0 // 清除预设金额选择
      return true
    },
    
    // 选择支付方式
    selectPaymentMethod(method) {
      this.selectedPaymentMethod = method
    },
    
    // 处理充值
    async handleRecharge() {
      if (!this.canRecharge) return
      
      this.loading = true
      
      try {
        const token = uni.getStorageSync('accessToken')
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/recharge/create`,
          method: 'POST',
          data: {
            userId: this.userId,
            amount: this.finalAmount,
            paymentMethod: this.selectedPaymentMethod,
            description: `账户充值${this.finalAmount}元`
          },
          header: { 'Access-Token': `Bearer ${token}` }
        })
        
        if (response.data.success) {
          const orderNo = response.data.data.orderNo
          
          // 这里应该调用第三方支付SDK
          // 模拟支付成功
          uni.showModal({
            title: '支付确认',
            content: `确认支付¥${this.finalAmount}？`,
            success: (res) => {
              if (res.confirm) {
                this.simulatePaymentSuccess(orderNo)
              }
            }
          })
        } else {
          uni.showToast({
            title: response.data.message || '创建充值订单失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('充值失败:', error)
        uni.showToast({
          title: '充值失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 模拟支付成功（实际应该通过支付回调处理）
    async simulatePaymentSuccess(orderNo) {
      try {
        const token = uni.getStorageSync('accessToken')
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/api/recharge/callback/success`,
          method: 'POST',
          data: {
            orderNo: orderNo,
            transactionId: 'TXN_' + Date.now(),
            callbackData: '模拟支付成功'
          },
          header: { 'Access-Token': `Bearer ${token}` }
        })
        
        if (response.data.success) {
          uni.showToast({
            title: '充值成功',
            icon: 'success'
          })
          
          // 刷新账户信息和充值记录
          this.loadAccountInfo()
          this.loadRechargeRecords()
          
          // 重置选择
          this.selectedAmount = 0
          this.customAmount = ''
          this.showCustomAmountInput = false
          this.selectedPaymentMethod = ''
        }
      } catch (error) {
        console.error('处理支付成功失败:', error)
      }
    },
    
    // 获取支付方式名称
    getPaymentMethodName(method) {
      const methods = {
        'WECHAT': '微信支付',
        'ALIPAY': '支付宝'
      }
      return methods[method] || method
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待支付',
        'SUCCESS': '支付成功',
        'FAILED': '支付失败',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        'PENDING': 'status-pending',
        'SUCCESS': 'status-success',
        'FAILED': 'status-failed',
        'CANCELLED': 'status-cancelled'
      }
      return classMap[status] || ''
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.recharge-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  color: white;
}

.balance-info {
  text-align: center;
  margin-bottom: 30rpx;
}

.balance-label {
  display: block;
  font-size: 28rpx;
  opacity: 0.9;
  margin-bottom: 10rpx;
}

.balance-amount {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
}

.recharge-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 24rpx;
  opacity: 0.8;
  margin-bottom: 5rpx;
}

.stat-value {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
}

/* 金额选择样式 */
.amount-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.amount-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.amount-item {
  background: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 15rpx;
  padding: 25rpx 15rpx;
  text-align: center;
  transition: all 0.3s ease;
}

.amount-item.active {
  background: #667eea;
  border-color: #667eea;
  color: white;
}

.amount-item.custom {
  background: #fff3cd;
  border-color: #ffeaa7;
}

.amount-item.custom.active {
  background: #667eea;
  border-color: #667eea;
  color: white;
}

.amount-text {
  font-size: 28rpx;
  font-weight: bold;
}

.custom-amount-input {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.amount-input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #ddd;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.amount-tip {
  font-size: 24rpx;
  color: #999;
}

/* 支付方式样式 */
.payment-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 25rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 15rpx;
  transition: all 0.3s ease;
}

.payment-method.active {
  border-color: #667eea;
  background: #f0f4ff;
}

.payment-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}

.payment-name {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.payment-check {
  width: 40rpx;
  height: 40rpx;
  background: #667eea;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

/* 充值按钮样式 */
.recharge-button-section {
  margin-bottom: 30rpx;
}

.recharge-button {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 50rpx;
  color: white;
  font-size: 32rpx;
  font-weight: bold;
}

.recharge-button.disabled {
  background: #ccc;
  color: #999;
}

.button-text {
  color: inherit;
}

/* 充值记录样式 */
.records-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.refresh-btn {
  color: #667eea;
  font-size: 28rpx;
}

.records-list {
  max-height: 600rpx;
  overflow-y: auto;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.record-item:last-child {
  border-bottom: none;
}

.record-info {
  display: flex;
  flex-direction: column;
}

.record-amount {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 5rpx;
}

.record-method {
  font-size: 24rpx;
  color: #666;
}

.record-status {
  text-align: right;
}

.status-text {
  display: block;
  font-size: 26rpx;
  margin-bottom: 5rpx;
}

.status-success {
  color: #28a745;
}

.status-pending {
  color: #ffc107;
}

.status-failed {
  color: #dc3545;
}

.status-cancelled {
  color: #6c757d;
}

.record-time {
  font-size: 22rpx;
  color: #999;
}

.empty-records {
  text-align: center;
  padding: 60rpx 0;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

/* 加载样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #333;
}
</style>
